<template>
  <div class="page-mobile_notice">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="isLogin ? '通知中心' : '公告中心'"
    ></white-header>
    <div class="menu-list" v-if="isLogin">
      <div class="menu-item" :class="['menu-item',active == 'notification'?'active':'']" @click="handleChange('notification')">
        <div class="icon">
          <img src="/img/mobile/notice.png" alt="">
        </div>
        <div class="name">通知中心</div>
      </div>
      <div class="menu-item" :class="['menu-item',active == 'notice'?'active':'']" @click="handleChange('notice')">
        <div class="icon">
          <img src="/img/mobile/notice.png" alt="">
        </div>
        <div class="name">公告中心</div>
      </div>
    </div>
    <div class="recommend-container">
      <div v-for="(item,index) in notice_list" :key="index" :class="['notice-box',readList.indexOf(item.id) != -1 ? '' : active == 'notice' ? '' : 'active']" @click="toPath(`/m/notice-detail?id=${item.id}`)">
        <div class="box-left">
          <div class="left-title">
            <span class="title-tips" v-if="active == 'notice'">公告：</span><span class="title-tips" v-else>通知：</span>{{item.name}}
          </div>
          <div class="left-bottom">
            <span style="margin-right:.2rem;">{{formatDate(item.startTime)}}</span>
            <!-- <span>发布者：某某某</span> -->
          </div>
        </div>
        <div class="box-right">
          <img src="/img/mobile/news_default.png" alt />
        </div>
      </div>
      <div class="no-data" v-if="notice_list.length == 0">
        <van-empty description="暂时没有信息哦~" />
      </div>
    </div>
  </div>
</template>

<script>
import { getNotice, getReadNotice } from "~/api/index";
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import NewsCard from '~/components/mobile/NewsCard.vue';
export default {
  scrollToTop: true,
  components: {
    WhiteHeader,
    NewsCard,
  },
  data() {
    return {
      page: 1,
      pageSize: 20,
      total: 0,
      notice_list: [],
      active: "notification",
      readList:[],
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      },
      token(state) {
        return state.token;
      },
    }),
    actived() {
      return this.$route.query.actived;
    },
    isLogin(){
      return this.token && Object.keys(this.user_info).length > 0;
    }
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    ...mapActions(["initNoticeList"]),
    async getReadNotice() {
      this.SET_IS_LOADING(true);
      let result = await getReadNotice(this.user_info.id);
      if (result && result.data && result.data.code == 200) {
        this.readList = result.data.data ? JSON.parse(result.data.data.readNoticeIds) : [];
      } else {
        this.$toast(this.$t("locale.mobile.notice.t5"));
        this.SET_IS_LOADING(false);
      }
    },
    formatDate(timestamp) {
      let date = new Date(timestamp);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      let add0 = (m) => {
        return m < 10 ? "0" + m : m;
      };
      let showTime = null;
      if (new Date(timestamp).toDateString() === new Date().toDateString()) {
        if (hour < 10) {
          showTime = "上午";
        } else if (hour < 12) {
          showTime = "中午";
        } else if (hour < 18) {
          showTime = "下午";
        } else {
          showTime = "晚上";
        }
        // console.log("今天", showTime + " " + add0(hour) + ":" + add0(minute));
        return showTime + " " + add0(hour) + ":" + add0(minute);
      } else {
        // console.log("以前", add0(year) + "/" + add0(month) + "/" + add0(day));
        return add0(year) + "/" + add0(month) + "/" + add0(day);
      }
    },
    toPath(path) {
      this.$router.push(path);
    },
    handleChange(name) {
      this.$router.replace({
        path: "/m/notice",
        query: {
          actived: name
        }
      });
      this.active = name;
      this.page = 1;
      this.getData();
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("上拉加载");
        if (this.total <= this.notice_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 300);
    },
    async getData(fetch_type) {
      this.SET_IS_LOADING(true);
      let result = await getNotice({
        sort: "id desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        isOpen: 1,
        type:
          this.active && this.active == "notification"
            ? 1
            : this.active && this.active == "notice"
            ? 2
            : 2
      });
      if (result && result.data.code == 200) {
        if (fetch_type == "pullup") {
          this.notice_list = [...this.notice_list, ...result.data.data.rows];
        } else {
          this.notice_list = result.data.data.rows;
        }
        this.total = result.data.data.total;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(this.$t("locale.mobile.notice.t5"));
      }
    }
  },
  activated() {
    if (process.client) {
      if (this.actived) {
        this.active = this.actived;
      } else {
        this.active = "notice";
        this.handleChange("notice");
      }
      this.getData();
      window.addEventListener("scroll", this.eventListener);
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.getReadNotice();
        return;
      }
    }
  },
  deactivated() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  created() {
    if (this.actived) {
      this.active = this.actived;
    } else {
      this.active = "notice";
      this.handleChange("notice");
    }
    this.getData();
    if (this.token && Object.keys(this.user_info).length > 0) {
        this.getReadNotice();
        return;
    }
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile_notice {
  width: 7.2rem;
  min-height: 100vh;
  background-color: #F2F3F5;
  .menu-list{
    // margin-top: .02rem;
    width: 7.2rem;
    height: 1.056rem;
    background-color: #ffffff;
    display: flex;
    .menu-item{
      width: 50%;
      height: 1.056rem;
      display: flex;
      justify-content: center;
      align-items: center;
      .icon{
        width: .384rem;
        height: .384rem;
        border-radius: 50%;
        overflow: hidden;
        background: #a1a5ac;
        margin-right: .2rem;
        img{
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .name{
        font-size: .3072rem;
        font-weight: bold;
        color: #9d9fa3;
      }
    }
    .menu-item.active{
      .icon{
        background: var(--theme-color);
      }
      .name{
        color: var(--theme-color);
      }
    }
  }
  .recommend-container{
    width: 7.2rem;
    .notice-box{
      width: 100%;
      height: 2.016rem;
      background: #ffffff;
      margin: .2rem 0;
      padding: 0 .3rem;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      .box-left{
        width: 4.8rem;
        height: 1.44rem;
        .left-title{
          font-size: .288rem;
          color: #494b4d;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          -webkit-box-orient: vertical;
          margin-bottom: .3rem;
          line-height: 0.35rem;
          height: 0.7rem;
        }
        .left-bottom{
          font-size: 0.26rem;
          color: #babec2;
        }
      }
      .box-right{
        width: 1.44rem;
        height: 1.44rem;
        overflow: hidden;
        border-radius: .1rem;
        img{
          width: 100%;
          height: 100%;
          display: block;
        }
      }
    }
    .notice-box.active{
      .title-tips{
        color: var(--theme-color);
      }
      &::after{
        content: "";
        display: block;
        width: .1rem;
        height: .1rem;
        border-radius: 50%;
        position: absolute;
        left: 0.1rem;
        top: 0.35rem;
        background: red;
      }

    }
  }
}
</style>
<style lang="scss">
.page-mobile_notice {
  
}
</style>
